package com.hncc.kumao.action;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.hncc.kumao.biz.IUserBiz;
import com.hncc.kumao.entity.User;
import com.hncc.kumao.exception.KumaoException;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.JWTUtils;
import com.hncc.kumao.util.JedisUtils;
import com.hncc.kumao.util.MyFileUtils;
import com.hncc.kumao.util.RandomUtils;

import redis.clients.jedis.Jedis;

/**
 * Action
 * 
 * @author chen
 *
 */
public class UserAction extends BaseAction {

    private IUserBiz userBiz;
    private File headPortrait;
    private String headPortraitFileName;
    private String headPortraitContentType;

    /**
     * 用户登录
     */
    public void login() {
        Jedis jedis = null;
        User loginUser = null;
        try {
            jedis = JedisUtils.getJedis();
            // 从Request中获取数据(这个数据来自拦截器)
            String jsonString = (String) getRequest().getAttribute(ConstValue.REQUEST_DATA);
            User user = JSON.parseObject(jsonString, User.class);
            String code = (String) JSON.parseObject(jsonString).get("authCode");
            // 校验数据
            if (user.getPhone() == null || user.getPhone().trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "手机号不能为空");
                return;
            }
            if (code != null) {
                // 验证码登录
                if (code == null || code.trim().length() <= 0) {
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码不能为空");
                    return;
                }
                // 从redis中获取验证码
                String authCode = jedis.get(user.getPhone());
                if (authCode == null || authCode.trim().length() <= 0) {
                    // 验证码错误
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码无效");
                    return;
                }
                if (authCode.equals(code)) {
                    // 验证码正确，根据手机号查询用户
                    loginUser = userBiz.getByPhone(user.getPhone());
                    if (loginUser == null) {
                        jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码错误");
                        return;
                    }
                } else {
                    // 验证码错误
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码错误");
                    return;
                }
            } else {
                // 密码登录
                if (user.getPassword() == null || user.getPassword().trim().length() <= 0) {
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "密码不能为空");
                    return;
                }
                // 根据手机号和密码获取用户
                loginUser = userBiz.getByPhoneAndPassword(user.getPhone(), user.getPassword());
                if (loginUser == null) {
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "手机号或密码错误");
                    return;
                }
            }
            // 删除验证码
            jedis.del(user.getPhone());
            // 根据id生成token并返回
            String token = JWTUtils.createJWT(loginUser.getId());
            String parseId = JWTUtils.parseJWT(token);
            // 以键值对的方式存入token
            jedis.hset(ConstValue.SERVER_TOKEN, parseId, loginUser.getId());
            // 返回token
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, token);
        } catch (KumaoException e) {
            e.printStackTrace();
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, e.getMessage());
            return;
        } catch (Exception e) {
            e.printStackTrace();
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            return;
        } finally {
            JedisUtils.closeJedis(jedis);
        }
    }

    /**
     * 用户登出
     */
    public void logout() {
        Jedis jedis = null;
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            // 从redis中删除键值
            jedis = JedisUtils.getJedis();
            jedis.hdel(ConstValue.SERVER_TOKEN, userId);
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "success");
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        } finally {
            JedisUtils.closeJedis(jedis);
        }
    }

    /**
     * 用户注册
     */
    public void regist() {
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getJedis();
            // 从Request中获取数据(这个数据来自拦截器)
            String jsonString = (String) getRequest().getAttribute(ConstValue.REQUEST_DATA);
            User user = JSON.parseObject(jsonString, User.class);
            String code = (String) JSON.parseObject(jsonString).get("authCode");
            //TODO 验证码 校验数据
            if(false) {
                if (code == null || code.trim().length() <= 0) {
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码不能为空");
                    return;
                }                
            }
            
            if (user.getPhone() == null || user.getPhone().trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "手机号不能为空");
                return;
            }
            if (user.getPassword() == null || user.getPassword().trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "密码不能为空");
                return;
            }
            if (user.getPassword().length() < 8) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "密码不能少于8位");
                return;
            }
            // 从redis中获取验证码
            String authCode = jedis.get(user.getPhone());
            //TODO 验证码
            if(false) {
                if (authCode == null || authCode.trim().length() <= 0) {
                    // 验证码错误
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码无效");
                    return;
                }                
            }
            
            if (true || authCode.equals(code)) {
                // 验证码正确，进行注册
                String userId = userBiz.regist(user);
                // 删除验证码
                jedis.del(user.getPhone());
                // 根据id生成token并返回
                String token = JWTUtils.createJWT(userId);
                String parseId = JWTUtils.parseJWT(token);
                // 以键值对的方式存入token
                jedis.hset(ConstValue.SERVER_TOKEN, parseId, userId);
                // 返回token
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, token);
            } else {
                // 验证码错误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "验证码错误");
                return;
            }
        } catch (KumaoException e) {
            e.printStackTrace();
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, e.getMessage());
            return;
        } catch (Exception e) {
            e.printStackTrace();
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            return;
        } finally {
            // 释放连接
            JedisUtils.closeJedis(jedis);
        }
    }

    /**
     * 获取用户信息
     */
    public void info() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            User user = userBiz.getById(userId);
            User userClone = (User) user.clone();
            userClone.setHeadPortraitUrl(ConstValue.BASE_RES_URL + user.getHeadPortraitUrl());
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, userClone);
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }

    /**
     * 设置用户信息
     */
    public void setInfo() {
        try {
            HttpServletRequest request = getRequest();
            String token = request.getParameter("token");
            String userId;
            try {
                // 手动校验令牌
                userId = checkToken(token);
            } catch (KumaoException e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            // User user = userBiz.getById(userId);
            String username = request.getParameter("username");
            String email = request.getParameter("email");
            // 校验数据
            if (username == null || username.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "用户名不能为空");
                return;
            }
            if (email == null || email.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "邮箱不能为空");
                return;
            }
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            // 处理头像问题
            File localFile = null;
            if (headPortrait != null) {
                // 判断是否支持该类型文件
                String suffix = MyFileUtils.getFileSuffix(headPortraitFileName).toLowerCase();
                if (ConstValue.IMAGE_TYPE.indexOf(suffix) == -1) {
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "不支持该类型文件");
                    return;
                }
                String fileUri = "/" + ConstValue.IMAGE_DIR_NAME + "/" + userId + "/"
                        + MyFileUtils.getUuidFileName(headPortraitFileName);
                String filePath = ConstValue.BASE_RES_PATH + fileUri;
                String fileUrl = ConstValue.BASE_RES_URL + fileUri;
                localFile = new File(filePath);
                user.setHeadPortraitUrl(fileUri);
            }
            // 调用业务层
            User resultUser = userBiz.setUserInfo(userId, user);
            // 拷贝文件
            if (localFile != null) {
                FileUtils.copyFile(headPortrait, localFile);
            }
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, resultUser);
        } catch (KumaoException e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, e.getMessage());
            e.printStackTrace();
            return;
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }

    /**
     * 生成验证码
     */
    public void createAuthCode() {
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getJedis();
            // 从Request中获取数据(这个数据来自拦截器)
            String jsonString = (String) getRequest().getAttribute(ConstValue.REQUEST_DATA);
            String phone = (String) JSON.parseObject(jsonString).get("phone");
            if (phone == null || phone.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "手机号不能为空");
                return;
            }
            String authCode = RandomUtils.randomCode();
            System.out.println("authCode: " + authCode);
            jedis.set(phone, authCode);
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "生成成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
        } finally {
            // 释放连接
            JedisUtils.closeJedis(jedis);
        }
    }

    public IUserBiz getUserBiz() {
        return userBiz;
    }

    public void setUserBiz(IUserBiz userBiz) {
        this.userBiz = userBiz;
    }

    public void setHeadPortrait(File headPortrait) {
        this.headPortrait = headPortrait;
    }

    public void setHeadPortraitFileName(String headPortraitFileName) {
        this.headPortraitFileName = headPortraitFileName;
    }

    public void setHeadPortraitContentType(String headPortraitContentType) {
        this.headPortraitContentType = headPortraitContentType;
    }
}
